<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller{

    // 授权登录(通过code换取openid)
    public function openid(Request $request){
        $code = $request->get('code');
        $type = $request->get('type');
        
        if($type == '1'){ // 商户
            $url='https://api.weixin.qq.com/sns/jscode2session?appid=wxd9d8c4e13a176553&secret=a2acc2517ce293b390f7834a80620f3e&js_code='.$code.'&grant_type=authorization_code';
        }else{ // 代理
            $url='https://api.weixin.qq.com/sns/jscode2session?appid=wx2101630f3dc4add0&secret=7bfa0969af783b4a6f91bf878535dc46&js_code='.$code.'&grant_type=authorization_code';
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $tmpInfo = curl_exec($curl);
        $tmpInfo=json_decode($tmpInfo,true);
        unset($tmpInfo['session_key']);
        curl_close($curl);
        
        if($type == '1'){ //判断查询代理/商户
            $user = DB::table('merchants')->where(['wx_openid' => $tmpInfo['openid']])->first();
        }else{ 
            $user = DB::table('users')->where(['wx_openid' => $tmpInfo['openid']])->first();
        }
        if(empty($user)){ //判断有没有授权登录
            $auth_status = 0;
        }else{
            $auth_status = 1;
            $tmpInfo['user'] = $user;
        }
        $tmpInfo['auth_status'] = $auth_status;
        
        return json_encode($tmpInfo);
    }
    
}